<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
    <title> - 天地维杰网</title>
    <meta name="keywords" content="系统架构,shutdown,不与天斗,Domino,博客,程序员,架构师,笔记,技术,分享,java,Redis">
    
    <meta property="og:title" content="">
    <meta property="og:site_name" content="天地维杰网">
    <meta property="og:image" content="/img/author.jpg"> 
    <meta name="title" content=" - 天地维杰网" />
    <meta name="description" content="天地维杰网 | 博客 | 软件 | 架构 | Java "> 
    <link rel="shortcut icon" href="http://www.shutdown.cn/img/favicon.ico" />
    <link rel="apple-touch-icon" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link rel="apple-touch-icon-precomposed" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link href="http://www.shutdown.cn/js/vendor/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/main.css" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/syntax.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
     fancybox: true, 
    motion: true
  };
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7826003325059020" crossorigin="anonymous"></script>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left page-home  ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-meta  custom-logo ">

  <div class="custom-logo-site-title">
    <a href="http://www.shutdown.cn"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">天地维杰网</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">人如秋鸿来有信，事若春梦了无痕</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
    <ul id="menu" class="menu">
      
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/redis/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-full"></i> <br />Redis
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/java/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-coffee"></i> <br />java
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/linux/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-linux"></i> <br />linux
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/daily/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bug"></i> <br />日常问题
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/spring/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-child"></i> <br />Spring和Springboot
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/mac/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-fire"></i> <br />Mac相关
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/middleware/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-gavel"></i> <br />中间件
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jiagou/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-rocket"></i> <br />架构
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/python/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-ship"></i> <br />python
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/front/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bolt"></i> <br />前端
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jvm/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-balance-scale"></i> <br />jvm
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/c/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-empty"></i> <br />c语言
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/web3/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-web3"></i> <br />web3
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/post/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/about/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于
          </a>
        </li>
      
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger"> <i class="menu-item-icon fa fa-search fa-fw"></i> <br /> 搜索</a>
      </li>
    </ul>
    <div class="site-search">
      <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>

    </div>
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
<section id="posts" class="posts-expand">
  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">
      <h1 class="post-title" itemprop="name headline">
        <a class="post-title-link" href="http://www.shutdown.cn/post/redis4.0%E6%96%B0%E7%89%B9%E6%80%A7%E4%BA%8C-psync2/" itemprop="url">
        
        </a>
      </h1>
      <div class="post-meta">
      <span class="post-time">
<span class="post-meta-item-icon">
    <i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">时间：</span>
<time itemprop="dateCreated" datetime="2016-03-22T13:04:35+08:00" content="0001-01-01">
    0001-01-01
</time>
</span> 
      
      
       <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读：</span>
<span class="leancloud-visitors-count">813 字 ~4分钟</span>
</span>
      </div>
    </header>
    <div class="post-body" itemprop="articleBody">
    

    

<h1 id="redis4-0新特性-二-psync2">Redis4.0新特性(二)-PSYNC2</h1>

<p>Redis4.0新特性psync2(partial resynchronization version2)部分重新同步(partial resync)增加版本；
主要解决Redis运维管理过程中，从实例重启和主实例故障切换等场景带来的全量重新同步(full resync)问题。</p>

<h3 id="什么是redis部分重新同步psync">什么是Redis部分重新同步psync</h3>

<p>redis部分重新同步：是指redis因某种原因引起复制中断后，从库重新同步时，只同步主实例的差异数据(写入指令），不进行bgsave复制整个RDB文件。</p>

<p>本文的名词规约：
部分重新同步：后文简称psync
全量重新同步：后文简称fullsync
redis2.8第一版部分重新同步：后文简称psync1
redis4.0第二版本部分重新同步：后文简称psync2</p>

<p>在说明psync2功能前，先简单阐述redis2.8版本发布的psync1</p>

<h4 id="redis2-8-psync1解决什么问题">Redis2.8 psync1解决什么问题</h4>

<p>在psync1功能出现前，redis复制秒级中断，就会触发从实例进行fullsync。
每一次的fullsync，集群的性能和资源使用都可能带来抖动；如果redis所处的网络环境不稳定，那么fullsync的出步频率可能较高。
为解决此问题，redis2.8引入psync1, 有效地解决这种复制闪断，带来的影响。</p>

<p>redis的fullsync对业务而言，算是比较“重”的影响；对性能和可用性都有一定危险。
这里列举几个fullsync常见的影响：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-csharp" data-lang="csharp">    <span style="color:#0000cf;font-weight:bold">1.</span> <span style="color:#000">master需运行bgsave</span><span style="color:#000;font-weight:bold">,</span><span style="color:#a40000">出</span><span style="color:#a40000">现</span><span style="color:#000">Fork</span><span style="color:#a40000">，</span><span style="color:#a40000">可</span><span style="color:#a40000">能</span><span style="color:#a40000">造</span><span style="color:#a40000">成</span><span style="color:#000">master达到毫秒或秒级的卡顿</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">latest_fork_usec</span><span style="color:#000;font-weight:bold">)</span><span style="color:#a40000">；</span>
    <span style="color:#0000cf;font-weight:bold">2.</span> <span style="color:#000">redis进程Fork导致Copy</span><span style="color:#000;font-weight:bold">-</span><span style="color:#000">On</span><span style="color:#000;font-weight:bold">-</span><span style="color:#000">Write内存使用消耗</span><span style="color:#000;font-weight:bold">(</span><span style="color:#a40000">后</span><span style="color:#a40000">文</span><span style="color:#a40000">简</span><span style="color:#a40000">称</span><span style="color:#000">COW</span><span style="color:#000;font-weight:bold">)</span><span style="color:#a40000">，</span><span style="color:#a40000">最</span><span style="color:#a40000">大</span><span style="color:#a40000">能</span><span style="color:#a40000">导</span><span style="color:#a40000">致</span><span style="color:#000">master进程内存使用量的消耗</span><span style="color:#a40000">。</span>    
    <span style="color:#000;font-weight:bold">(</span><span style="color:#000">eg</span> <span style="color:#000">RDB</span><span style="color:#000;font-weight:bold">:</span> <span style="color:#0000cf;font-weight:bold">5</span><span style="color:#0000cf;font-weight:bold">2</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#0000cf;font-weight:bold">3</span> <span style="color:#000">MB</span> <span style="color:#000">of</span> <span style="color:#000">memory</span> <span style="color:#000">used</span> <span style="color:#204a87;font-weight:bold">by</span> <span style="color:#000">copy</span><span style="color:#000;font-weight:bold">-</span><span style="color:#204a87;font-weight:bold">on</span><span style="color:#000;font-weight:bold">-</span><span style="color:#000">write</span><span style="color:#000;font-weight:bold">)</span>
    <span style="color:#0000cf;font-weight:bold">3.</span> <span style="color:#000">Redis</span> <span style="color:#000">Slave</span> <span style="color:#000">load</span> <span style="color:#000">RDB过程</span><span style="color:#a40000">，</span><span style="color:#a40000">会</span><span style="color:#a40000">导</span><span style="color:#a40000">致</span><span style="color:#a40000">复</span><span style="color:#a40000">制</span><span style="color:#a40000">线</span><span style="color:#a40000">程</span><span style="color:#a40000">的</span><span style="color:#000">client</span> <span style="color:#000">output</span> <span style="color:#000">buffer增长很大</span><span style="color:#a40000">；</span><span style="color:#a40000">增</span><span style="color:#a40000">大</span><span style="color:#000">Master进程内存消耗</span><span style="color:#a40000">；</span>
    <span style="color:#0000cf;font-weight:bold">4.</span> <span style="color:#000">Redis保存RDB</span><span style="color:#000;font-weight:bold">(</span><span style="color:#a40000">不</span><span style="color:#a40000">考</span><span style="color:#a40000">虑</span><span style="color:#000">disless</span> <span style="color:#000">replication</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">,</span><span style="color:#a40000">导</span><span style="color:#a40000">致</span><span style="color:#a40000">服</span><span style="color:#a40000">务</span><span style="color:#a40000">器</span><span style="color:#a40000">磁</span><span style="color:#a40000">盘</span><span style="color:#000">IO和CPU</span><span style="color:#000;font-weight:bold">(</span><span style="color:#a40000">压</span><span style="color:#a40000">缩</span><span style="color:#000;font-weight:bold">)</span><span style="color:#a40000">资</span><span style="color:#a40000">源</span><span style="color:#a40000">消</span><span style="color:#a40000">耗</span>
    <span style="color:#0000cf;font-weight:bold">5.</span> <span style="color:#a40000">发</span><span style="color:#a40000">送</span><span style="color:#a40000">数</span><span style="color:#000">GB大小的RDB文件</span><span style="color:#000;font-weight:bold">,</span><span style="color:#a40000">会</span><span style="color:#a40000">导</span><span style="color:#a40000">致</span><span style="color:#a40000">服</span><span style="color:#a40000">务</span><span style="color:#a40000">器</span><span style="color:#a40000">网</span><span style="color:#a40000">络</span><span style="color:#a40000">出</span><span style="color:#a40000">口</span><span style="color:#a40000">爆</span><span style="color:#a40000">增</span><span style="color:#000;font-weight:bold">,</span><span style="color:#a40000">如</span><span style="color:#a40000">果</span><span style="color:#a40000">千</span><span style="color:#a40000">兆</span><span style="color:#a40000">网</span><span style="color:#a40000">卡</span><span style="color:#a40000">服</span><span style="color:#a40000">务</span><span style="color:#a40000">器</span><span style="color:#a40000">，</span><span style="color:#a40000">期</span><span style="color:#a40000">间</span><span style="color:#a40000">会</span><span style="color:#a40000">影</span><span style="color:#a40000">响</span><span style="color:#a40000">业</span><span style="color:#a40000">务</span><span style="color:#a40000">正</span><span style="color:#a40000">常</span><span style="color:#a40000">请</span><span style="color:#a40000">求</span><span style="color:#a40000">响</span><span style="color:#a40000">应</span><span style="color:#a40000">时</span><span style="color:#a40000">间</span><span style="color:#000;font-weight:bold">(</span><span style="color:#a40000">以</span><span style="color:#a40000">及</span><span style="color:#a40000">其</span><span style="color:#a40000">他</span><span style="color:#a40000">连</span><span style="color:#a40000">锁</span><span style="color:#a40000">影</span><span style="color:#a40000">响</span><span style="color:#000;font-weight:bold">)</span>
</code></pre></div>
<h4 id="psync1的基本实现">psync1的基本实现</h4>

<p>redis2.8为支持psync1，引入了replication backlog buffer(后文称：复制积压缓冲区）；</p>

<p>复制积压缓冲区是redis维护的固定长度缓冲队列(由参数repl-backlog-size设置，默认1MB)，
master的写入命令在同步给slaves的同时，会在缓冲区中写入一份(master只有1个积压缓冲区，所有slaves共享）。</p>

<p>当redis复制中断后，slave会尝试采用psync, 上报原master runid + 当前已同步master的offset(复制偏移量，类似mysql的binlog file和position)；
如果runid与master的一致，且复制偏移量在master的复制积压缓冲区中还有(即offset &gt;= min(backlog值)，master就认为部分重同步成功，不再进行全量同步。</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-css" data-lang="css"><span style="color:#204a87;font-weight:bold">部分重同步成功</span><span style="color:#a40000">，</span><span style="color:#204a87;font-weight:bold">master的日志显示如下</span><span style="color:#a40000">：</span>

<span style="color:#204a87;font-weight:bold">30422</span><span style="color:#000;font-weight:bold">:</span><span style="color:#5c35cc;font-weight:bold">M</span> <span style="color:#204a87;font-weight:bold">04</span> <span style="color:#204a87;font-weight:bold">Aug</span> <span style="color:#204a87;font-weight:bold">14</span><span style="color:#000;font-weight:bold">:</span><span style="color:#5c35cc;font-weight:bold">33</span><span style="color:#000;font-weight:bold">:</span><span style="color:#5c35cc;font-weight:bold">48</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">505</span> <span style="color:#ce5c00;font-weight:bold">*</span> <span style="color:#204a87;font-weight:bold">Slave</span> <span style="color:#204a87;font-weight:bold">xxxxx</span><span style="color:#000;font-weight:bold">:</span><span style="color:#5c35cc;font-weight:bold">10005</span> <span style="color:#204a87;font-weight:bold">asks</span> <span style="color:#204a87;font-weight:bold">for</span> <span style="color:#204a87;font-weight:bold">synchronization</span>
<span style="color:#204a87;font-weight:bold">30422</span><span style="color:#000;font-weight:bold">:</span><span style="color:#5c35cc;font-weight:bold">M</span> <span style="color:#204a87;font-weight:bold">04</span> <span style="color:#204a87;font-weight:bold">Aug</span> <span style="color:#204a87;font-weight:bold">14</span><span style="color:#000;font-weight:bold">:</span><span style="color:#5c35cc;font-weight:bold">33</span><span style="color:#000;font-weight:bold">:</span><span style="color:#5c35cc;font-weight:bold">48</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">506</span> <span style="color:#ce5c00;font-weight:bold">*</span> <span style="color:#204a87;font-weight:bold">Partial</span> <span style="color:#204a87;font-weight:bold">resynchronization</span> <span style="color:#204a87;font-weight:bold">request</span> <span style="color:#204a87;font-weight:bold">from</span> <span style="color:#204a87;font-weight:bold">xxx</span><span style="color:#000;font-weight:bold">:</span><span style="color:#5c35cc;font-weight:bold">10005</span> <span style="color:#204a87;font-weight:bold">accepted</span><span style="color:#ce5c00;font-weight:bold">.</span> <span style="color:#204a87;font-weight:bold">Sending</span> <span style="color:#204a87;font-weight:bold">0</span> <span style="color:#204a87;font-weight:bold">bytes</span> <span style="color:#204a87;font-weight:bold">of</span> <span style="color:#204a87;font-weight:bold">backlog</span> <span style="color:#204a87;font-weight:bold">starting</span> <span style="color:#204a87;font-weight:bold">from</span> <span style="color:#204a87;font-weight:bold">offset</span> <span style="color:#204a87;font-weight:bold">6448313</span><span style="color:#ce5c00;font-weight:bold">.</span></code></pre></div>
<p>redis2.8的部分同步机制，有效解决了网络环境不稳定、redis执行高时间复杂度的命令引起的复制中断，从而导致全量同步。但在应对slave重启和Master故障切换的场景时，psync1还是需进行全量同步。</p>

<h4 id="psync1的不足">psync1的不足</h4>

<p>从上文可知，psync1需2个条件同时满足，才能成功psync: master runid不变 和复制偏移量在master复制积缓冲区中。
那么在redis slave重启,因master runid和复制偏移量都会丢失，需进行全量重同步；
redis master发生故障切换，因master runid发生了变化；故障切换后，新的slave需进行全量重同步。</p>

<p>而slave维护性重启、master故障切换都是redis运维常见场景，为redis的psync1是不能解决这两类场景的成功部分重同步问题。</p>

<p>因此redis4.0的加强版部分重同步功能-psync2，主要解决这两类场景的部分重新同步。</p>

<h3 id="psync2的实现简述">psync2的实现简述</h3>

<p>在redis cluster的实际生产运营中，实例的维护性重启、主实例的故障切换（如cluster failover)操作都是比较常见的(如实例升级、rename command和释放实例内存碎片等）。而在redis4.0版本前，这类维护性的处理，redis都会发生全量重新同步，导到性能敏感的服务有少量受损。
如前文所述，psync2主要让redis在从实例重启和主实例故障切换场景下，也能使用部分重新同步。
本节主要简述psync2在这两种场景的逻辑实现。
名词解释：</p>

<ul>
<li>master_replid : 复制ID1(后文简称：replid1)，一个长度为41个字节(40个随机串+&rsquo;\0&rsquo;)的字符串。redis实例都有，和runid没有直接关联，但和runid生成规则相同，都是由getRandomHexChars函数生成。当实例变为从实例后，自己的replid1会被主实例的replid1覆盖。</li>
<li>master_replid2：复制ID2(后文简称:replid2),默认初始化为全0，用于存储上次主实例的replid1</li>
</ul>

<p>实例的replid信息，可通过info replication进行查看； 示例如下：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-csharp" data-lang="csharp"><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#0000cf;font-weight:bold">2</span><span style="color:#0000cf;font-weight:bold">7.0</span><span style="color:#000;font-weight:bold">.</span><span style="color:#0000cf;font-weight:bold">0.1</span><span style="color:#000;font-weight:bold">:</span><span style="color:#0000cf;font-weight:bold">6</span><span style="color:#0000cf;font-weight:bold">3</span><span style="color:#0000cf;font-weight:bold">8</span><span style="color:#0000cf;font-weight:bold">5</span><span style="color:#000;font-weight:bold">&gt;</span> <span style="color:#000">info</span> <span style="color:#000">replication</span>
<span style="color:#a40000">#</span> <span style="color:#000">Replication</span>
<span style="color:#000">role</span><span style="color:#000;font-weight:bold">:</span><span style="color:#000">slave</span>
<span style="color:#000">master_host</span><span style="color:#000;font-weight:bold">:</span><span style="color:#000">xxxx</span>      <span style="color:#8f5902;font-style:italic">// IP模糊处理
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#000">master_port</span><span style="color:#000;font-weight:bold">:</span><span style="color:#0000cf;font-weight:bold">6</span><span style="color:#0000cf;font-weight:bold">3</span><span style="color:#0000cf;font-weight:bold">8</span><span style="color:#0000cf;font-weight:bold">2</span>
<span style="color:#000">master_link_status</span><span style="color:#000;font-weight:bold">:</span><span style="color:#000">up</span>
<span style="color:#000">slave_repl_offset</span><span style="color:#000;font-weight:bold">:</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#0000cf;font-weight:bold">9</span><span style="color:#0000cf;font-weight:bold">7</span><span style="color:#0000cf;font-weight:bold">5</span><span style="color:#0000cf;font-weight:bold">0</span>
<span style="color:#000">master_replid</span><span style="color:#000;font-weight:bold">:</span><span style="color:#000">fe093add4ab71544ce6508d2e0bf1dd0b7d1c5b2</span>  <span style="color:#8f5902;font-style:italic">//这里是主实例的replid1相同
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#000">master_replid2</span><span style="color:#000;font-weight:bold">:</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#0000cf;font-weight:bold">0</span>  <span style="color:#8f5902;font-style:italic">//未发生切换，即主实例未发生过变化，所以是初始值全&#34;0&#34;
</span><span style="color:#8f5902;font-style:italic"></span><span style="color:#000">master_repl_offset</span><span style="color:#000;font-weight:bold">:</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#0000cf;font-weight:bold">9</span><span style="color:#0000cf;font-weight:bold">7</span><span style="color:#0000cf;font-weight:bold">5</span><span style="color:#0000cf;font-weight:bold">0</span>
<span style="color:#000">second_repl_offset</span><span style="color:#000;font-weight:bold">:</span><span style="color:#000;font-weight:bold">-</span><span style="color:#0000cf;font-weight:bold">1</span>
</code></pre></div>
<h4 id="redis从实例重启的部分重新同步">Redis从实例重启的部分重新同步</h4>

<p>在之前的版本，redis重启后，复制信息是完全丢失;所以从实例重启后，只能进行全量重新同步。
redis4.0为实现重启后，仍可进行部分重新同步，主要做以下3点：
1 redis关闭时，把复制信息作为辅助字段(AUX Fields)存储在RDB文件中；以实现同步信息持久化。
2 redis启动加载RDB文件时，会把复制信息赋给相关字段；为部分同步
3 redis重新同步时，会上报repl-id和repl-offset同步信息，如果和主实例匹配，且offset还在主实例的复制积压缓冲区内，则只进行部分重新同步。</p>

<p>接下来，我们详细分析每步的简单实现</p>

<h5 id="redis关闭时-持久化复制信息到rdb">redis关闭时，持久化复制信息到RDB</h5>

<p>redis在关闭时，通过shutdown save,都会调用rdbSaveInfoAuxFields函数，
把当前实例的repl-id和repl-offset保存到RDB文件中。
说明：当前的RDB存储的数据内容和复制信息是一致性的。熟悉MySQL的同学，可以认为MySQL中全量备份数和binlog信息是一致的。
rdbSaveInfoAuxFields函数实现在rdb.c源文件中，省略后代码如下：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-kotlin" data-lang="kotlin"><span style="color:#8f5902;font-style:italic">/* Save a few default AUX fields with information about the RDB generated. */</span>
<span style="color:#000">int</span> <span style="color:#000">rdbSaveInfoAuxFields</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">rio</span> <span style="color:#000;font-weight:bold">*</span><span style="color:#000">rdb</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">int</span> <span style="color:#000">flags</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">rdbSaveInfo</span> <span style="color:#000;font-weight:bold">*</span><span style="color:#000">rsi</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">{</span>

    <span style="color:#8f5902;font-style:italic">/* Add a few fields about the state when the RDB was created. */</span>
    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">rdbSaveAuxFieldStrStr</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">rdb</span><span style="color:#000;font-weight:bold">,</span><span style="color:#4e9a06">&#34;redis-ver&#34;</span><span style="color:#000;font-weight:bold">,</span><span style="color:#000">REDIS_VERSION</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">=</span><span style="color:#000;font-weight:bold">=</span> <span style="color:#000;font-weight:bold">-</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#204a87;font-weight:bold">return</span> <span style="color:#000;font-weight:bold">-</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">;</span>
    
    <span style="color:#8f5902;font-style:italic">//把实例的repl-id和repl-offset作为辅助字段，存储在RDB中
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">rdbSaveAuxFieldStrStr</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">rdb</span><span style="color:#000;font-weight:bold">,</span><span style="color:#4e9a06">&#34;repl-id&#34;</span><span style="color:#000;font-weight:bold">,</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">=</span><span style="color:#000;font-weight:bold">=</span> <span style="color:#000;font-weight:bold">-</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#204a87;font-weight:bold">return</span> <span style="color:#000;font-weight:bold">-</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">;</span>
    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">rdbSaveAuxFieldStrInt</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">rdb</span><span style="color:#000;font-weight:bold">,</span><span style="color:#4e9a06">&#34;repl-offset&#34;</span><span style="color:#000;font-weight:bold">,</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">master_repl_offset</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">=</span><span style="color:#000;font-weight:bold">=</span> <span style="color:#000;font-weight:bold">-</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#204a87;font-weight:bold">return</span> <span style="color:#000;font-weight:bold">-</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">;</span>
    <span style="color:#204a87;font-weight:bold">return</span> <span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">;</span>
<span style="color:#000;font-weight:bold">}</span></code></pre></div>
<p>生成的RDB文件，可以通过redis自带的redis-check-rdb工具查看辅助字段信息。
其中repl两字段信息和info中的相同；</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-csharp" data-lang="csharp"><span style="color:#a40000">$</span><span style="color:#000">shell</span><span style="color:#000;font-weight:bold">&gt;</span> <span style="color:#000;font-weight:bold">/</span><span style="color:#000">src</span><span style="color:#000;font-weight:bold">/</span><span style="color:#000">redis</span><span style="color:#000;font-weight:bold">-</span><span style="color:#000">check</span><span style="color:#000;font-weight:bold">-</span><span style="color:#000">rdb</span>  <span style="color:#000">dump</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">rdb</span>      
<span style="color:#c4a000">[offset 0]</span> <span style="color:#000">Checking</span> <span style="color:#000">RDB</span> <span style="color:#000">file</span> <span style="color:#000">dump</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">rdb</span>
<span style="color:#c4a000">[offset 26]</span> <span style="color:#000">AUX</span> <span style="color:#000">FIELD</span> <span style="color:#000">redis</span><span style="color:#000;font-weight:bold">-</span><span style="color:#000">ver</span> <span style="color:#000;font-weight:bold">=</span> <span style="color:#a40000">&#39;</span><span style="color:#0000cf;font-weight:bold">4.0</span><span style="color:#000;font-weight:bold">.</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#a40000">&#39;</span>
<span style="color:#c4a000">[offset 133]</span> <span style="color:#000">AUX</span> <span style="color:#000">FIELD</span> <span style="color:#000">repl</span><span style="color:#000;font-weight:bold">-</span><span style="color:#000">id</span> <span style="color:#000;font-weight:bold">=</span> <span style="color:#a40000">&#39;</span><span style="color:#0000cf;font-weight:bold">4</span><span style="color:#0000cf;font-weight:bold">4</span><span style="color:#0000cf;font-weight:bold">8</span><span style="color:#0000cf;font-weight:bold">7</span><span style="color:#0000cf;font-weight:bold">3f</span><span style="color:#0000cf;font-weight:bold">8</span><span style="color:#0000cf;font-weight:bold">3</span><span style="color:#0000cf;font-weight:bold">9</span><span style="color:#000">ae3a57572920cdaf70399672b842691</span><span style="color:#a40000">&#39;</span>
<span style="color:#c4a000">[offset 148]</span> <span style="color:#000">AUX</span> <span style="color:#000">FIELD</span> <span style="color:#000">repl</span><span style="color:#000;font-weight:bold">-</span><span style="color:#000">offset</span> <span style="color:#000;font-weight:bold">=</span> <span style="color:#4e9a06">&#39;0&#39;</span>
<span style="color:#c4a000">[offset 167]</span> <span style="color:#000">o</span><span style="color:#000;font-weight:bold">/</span> <span style="color:#000">RDB</span> <span style="color:#000">looks</span> <span style="color:#000">OK</span><span style="color:#000;font-weight:bold">!</span> <span style="color:#a40000">\</span><span style="color:#000">o</span><span style="color:#000;font-weight:bold">/</span>
<span style="color:#c4a000">[info]</span> <span style="color:#0000cf;font-weight:bold">1</span> <span style="color:#000">keys</span> <span style="color:#000">read</span>
<span style="color:#c4a000">[info]</span> <span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">expires</span>
<span style="color:#c4a000">[info]</span> <span style="color:#0000cf;font-weight:bold">0</span> <span style="color:#000">already</span> <span style="color:#000">expired</span>
</code></pre></div>
<h5 id="redis启动读取rdb中复制信息">redis启动读取RDB中复制信息</h5>

<p>redis实例启动读取RDB文件，通过rdb.c文件中rdbLoadRio()函数实现。
redis加载RDB文件，会专门处理文件中辅助字段(AUX fields）信息，把其中repl_id和repl_offset加载到实例中，分别赋给master_replid和master_repl_offset两个变量值。
以下代码，是从RDB文件中读取两个辅助字段值。</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">int rdbLoadRio(rio *rdb, rdbSaveInfo *rsi) {
----------省略-----------

else if (!strcasecmp(auxkey-&gt;ptr,&#34;repl-id&#34;)) {//读取的aux字段是repl-id
                if (rsi <span style="color:#a40000">&amp;</span><span style="color:#a40000">&amp;</span> sdslen(auxval-&gt;ptr) == CONFIG_RUN_ID_SIZE) {
                    memcpy(rsi-&gt;repl_id,auxval-&gt;ptr,CONFIG_RUN_ID_SIZE+1);
                    rsi-&gt;repl_id_is_set = 1;
                }
            } else if (!strcasecmp(auxkey-&gt;ptr,&#34;repl-offset&#34;)) { 
                if (rsi) rsi-&gt;repl_offset = strtoll(auxval-&gt;ptr,NULL,10);
            } else {
                /* We ignore fields we don&#39;t understand, as by AUX field
                 * contract. */
                serverLog(LL_DEBUG,&#34;Unrecognized RDB AUX field: &#39;%s&#39;&#34;,
                    (char*)auxkey-&gt;ptr);
            }
}</code></pre></div>
<h5 id="redis从实例尝试部分重新同步">redis从实例尝试部分重新同步</h5>

<p>redis实例重启后，从RDB文件中加载(注：此处不讨论AOF和RDB加载优先权）master_replid和master_repl_offset；相当于实例的server.cached_master。当我们把它作为某个实例的从库时（包含如被动的cluster slave或主动执行slaveof指令)，实例向主实例上报master_replid和master_repl_offset+1；从实例同时满足以下两条件，就可以部分重新同步：
1 从实例上报master_replid串，与主实例的master_replid1或replid2有一个相等
2 从实例上报的master_repl_offset+1字节，还存在于主实例的复制积压缓冲区中</p>

<p>从实例尝试部分重新同步函数slaveTryPartialResynchronization(replication.c文件中）；
主实例判断能否进行部分重新同步函数masterTryPartialResynchronization（replication.c文件中）。</p>

<h5 id="redis重启时-临时调整主实例的复制积压缓冲区大小">redis重启时，临时调整主实例的复制积压缓冲区大小</h5>

<p>redis的复制积压缓冲区是通过参数repl-backlog-size设置，默认1MB；为确保从实例重启后，还能部分重新同步，需设置合理的repl-backlog-size值。
1 计算合理的repl-backlog-size值大小
通过主库每秒增量的master复制偏移量master_repl_offset(info replication指令获取)大小，
如每秒offset增加是5MB,那么主实例复制积压缓冲区要保留最近60秒写入内容，backlog_size设置就得大于300MB(60*5)。而从实例重启加载RDB文件是较耗时的过程，如重启某个重实例需120秒(RDB大小和CPU配置相关），那么主实例backlog_size就得设置至少600MB.</p>

<p>计算公式：backlog_size = 重启从实例时长 * 主实例offset每秒写入量</p>

<p>2 重启从实例前，调整主实例的动态调整repl-backlog-size的值。
通过config set动态调整redis的repl-backlog-size时，redis会释放当前的积压缓冲区，重新分配一个指定大小的缓冲区。 所以我们必须在从实例重启前，调整主实例的repl-backlog-size。
调整backlog_size处理函数resizeReplicationBacklog，代码逻辑如下：</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#204a87;font-weight:bold">void</span> <span style="color:#000">resizeReplicationBacklog</span><span style="color:#000;font-weight:bold">(</span><span style="color:#204a87;font-weight:bold">long</span> <span style="color:#204a87;font-weight:bold">long</span> <span style="color:#000">newsize</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">{</span>
    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">newsize</span> <span style="color:#ce5c00;font-weight:bold">&lt;</span> <span style="color:#000">CONFIG_REPL_BACKLOG_MIN_SIZE</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#8f5902;font-style:italic">//�如果设置新值小于16KB,则修改为16KB
</span><span style="color:#8f5902;font-style:italic"></span>        <span style="color:#000">newsize</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">CONFIG_REPL_BACKLOG_MIN_SIZE</span><span style="color:#000;font-weight:bold">;</span>
    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_size</span> <span style="color:#ce5c00;font-weight:bold">=</span><span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">newsize</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#204a87;font-weight:bold">return</span><span style="color:#000;font-weight:bold">;</span> <span style="color:#8f5902;font-style:italic">//如果新值与原值相同，则不作任何处理，直接返回。
</span><span style="color:#8f5902;font-style:italic"></span>
    <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_size</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">newsize</span><span style="color:#000;font-weight:bold">;</span>  <span style="color:#8f5902;font-style:italic">//修改backlog参数大小
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog</span> <span style="color:#ce5c00;font-weight:bold">!</span><span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#204a87">NULL</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">{</span> <span style="color:#8f5902;font-style:italic">//当backlog内容非空时，释放当前backlog，并按新值分配一个新的backlog
</span><span style="color:#8f5902;font-style:italic"></span>        <span style="color:#8f5902;font-style:italic">/* What we actually do is to flush the old buffer and realloc a new
</span><span style="color:#8f5902;font-style:italic">         * empty one. It will refill with new data incrementally.
</span><span style="color:#8f5902;font-style:italic">         * The reason is that copying a few gigabytes adds latency and even
</span><span style="color:#8f5902;font-style:italic">         * worse often we need to alloc additional space before freeing the
</span><span style="color:#8f5902;font-style:italic">         * old buffer. */</span>
        <span style="color:#000">zfree</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
        <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">zmalloc</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_size</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
        <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_histlen</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#0000cf;font-weight:bold">0</span><span style="color:#000;font-weight:bold">;</span>  <span style="color:#8f5902;font-style:italic">//修改backlog内容长度和首字节offset都为0
</span><span style="color:#8f5902;font-style:italic"></span>        <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_idx</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#0000cf;font-weight:bold">0</span><span style="color:#000;font-weight:bold">;</span>
        <span style="color:#8f5902;font-style:italic">/* Next byte we have is... the next since the buffer is empty. */</span>
        <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_off</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">master_repl_offset</span><span style="color:#ce5c00;font-weight:bold">+</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">;</span>
    <span style="color:#000;font-weight:bold">}</span>
<span style="color:#000;font-weight:bold">}</span>
</code></pre></div>
<h3 id="psync2实现redis-cluster-failover部分全新同步">psync2实现Redis Cluster Failover部分全新同步</h3>

<p>为解决主实例故障切换后，重新同步新主实例数据时使用psync，而分fullsync；</p>

<p>1 redis4.0使用两组replid、offset替换原来的master runid和offset.
2 redis slave默认开启复制积压缓冲区功能；以便slave故障切换变化master后，其他落后从可以从缓冲区中获取写入指令。
第一组：master_replid和master_repl_offset
如果redis是主实例，则表示为自己的replid和复制偏移量； 如果redis是从实例，则表示为自己主实例的replid1和同步主实例的复制偏移量。</p>

<p>第二组：master_replid2和second_repl_offset
无论主从，都表示自己上次主实例repid1和复制偏移量；用于兄弟实例或级联复制，主库故障切换psync.
初始化时, 前者是40个字符长度为0，后者是-1； 只有当主实例发生故障切换时，redis把自己replid1和master_repl_offset+1分别赋值给master_replid2和second_repl_offset。
这个交换逻辑实现在函数shiftReplicationId中。</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#204a87;font-weight:bold">void</span> <span style="color:#000">shiftReplicationId</span><span style="color:#000;font-weight:bold">(</span><span style="color:#204a87;font-weight:bold">void</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">{</span>
    <span style="color:#000">memcpy</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid2</span><span style="color:#000;font-weight:bold">,</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid</span><span style="color:#000;font-weight:bold">,</span><span style="color:#204a87;font-weight:bold">sizeof</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span> <span style="color:#8f5902;font-style:italic">//replid赋值给replid2
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#8f5902;font-style:italic">/* We set the second replid offset to the master offset + 1, since
</span><span style="color:#8f5902;font-style:italic">     * the slave will ask for the first byte it has not yet received, so
</span><span style="color:#8f5902;font-style:italic">     * we need to add one to the offset: for example if, as a slave, we are
</span><span style="color:#8f5902;font-style:italic">     * sure we have the same history as the master for 50 bytes, after we
</span><span style="color:#8f5902;font-style:italic">     * are turned into a master, we can accept a PSYNC request with offset
</span><span style="color:#8f5902;font-style:italic">     * 51, since the slave asking has the same history up to the 50th
</span><span style="color:#8f5902;font-style:italic">     * byte, and is asking for the new bytes starting at offset 51. */</span>
    <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">second_replid_offset</span> <span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">master_repl_offset</span><span style="color:#ce5c00;font-weight:bold">+</span><span style="color:#0000cf;font-weight:bold">1</span><span style="color:#000;font-weight:bold">;</span> 
    <span style="color:#000">changeReplicationId</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
    <span style="color:#000">serverLog</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">LL_WARNING</span><span style="color:#000;font-weight:bold">,</span><span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">Setting secondary replication ID to %s, valid up to offset: %lld. New replication ID is %s</span><span style="color:#4e9a06">&#34;</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid2</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">second_replid_offset</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
<span style="color:#000;font-weight:bold">}</span>
</code></pre></div>
<p>这样发生主库故障切换，以下三种常见结构，都能进行psync:
1 一主一从发生切换，A-&gt;B 切换变成 B-&gt;A ;
2 一主多从发生切换，兄弟节点变成父子节点时；
3 级别复制发生切换， A-&gt;B-&gt;C 切换变成 B-&gt;C-&gt;A</p>

<p>主实例判断能否进行psync的逻辑函数在masterTryPartialResynchronization()</p>
<div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#204a87;font-weight:bold">int</span> <span style="color:#000">masterTryPartialResynchronization</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">client</span> <span style="color:#ce5c00;font-weight:bold">*</span><span style="color:#000">c</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">{</span>
 
    <span style="color:#8f5902;font-style:italic">//如果slave提供的master_replid与master的replid不同，且与master的replid2不同，或同步速度快于master； 就必须进行fullsync.
</span><span style="color:#8f5902;font-style:italic"></span>    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">strcasecmp</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">master_replid</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#ce5c00;font-weight:bold">&amp;</span>
        <span style="color:#000;font-weight:bold">(</span><span style="color:#000">strcasecmp</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">master_replid</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid2</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">|</span><span style="color:#ce5c00;font-weight:bold">|</span>
         <span style="color:#000">psync_offset</span> <span style="color:#ce5c00;font-weight:bold">&gt;</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">second_replid_offset</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">)</span>
    <span style="color:#000;font-weight:bold">{</span>
        <span style="color:#8f5902;font-style:italic">/* Run id &#34;?&#34; is used by slaves that want to force a full resync. */</span>
        <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">master_replid</span><span style="color:#000;font-weight:bold">[</span><span style="color:#0000cf;font-weight:bold">0</span><span style="color:#000;font-weight:bold">]</span> <span style="color:#ce5c00;font-weight:bold">!</span><span style="color:#ce5c00;font-weight:bold">=</span> <span style="color:#4e9a06"></span><span style="color:#4e9a06">&#39;</span><span style="color:#4e9a06">?</span><span style="color:#4e9a06">&#39;</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">{</span>
            <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">strcasecmp</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">master_replid</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#ce5c00;font-weight:bold">&amp;</span><span style="color:#ce5c00;font-weight:bold">&amp;</span>
                <span style="color:#000">strcasecmp</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">master_replid</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid2</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">)</span>
            <span style="color:#000;font-weight:bold">{</span>
                <span style="color:#000">serverLog</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">LL_NOTICE</span><span style="color:#000;font-weight:bold">,</span><span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">Partial resynchronization not accepted: </span><span style="color:#4e9a06">&#34;</span>
                    <span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">Replication ID mismatch (Slave asked for &#39;%s&#39;, my </span><span style="color:#4e9a06">&#34;</span>
                    <span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">replication IDs are &#39;%s&#39; and &#39;%s&#39;)</span><span style="color:#4e9a06">&#34;</span><span style="color:#000;font-weight:bold">,</span>
                    <span style="color:#000">master_replid</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">replid2</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
            <span style="color:#000;font-weight:bold">}</span> <span style="color:#204a87;font-weight:bold">else</span> <span style="color:#000;font-weight:bold">{</span>
                <span style="color:#000">serverLog</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">LL_NOTICE</span><span style="color:#000;font-weight:bold">,</span><span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">Partial resynchronization not accepted: </span><span style="color:#4e9a06">&#34;</span>
                    <span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">Requested offset for second ID was %lld, but I can reply </span><span style="color:#4e9a06">&#34;</span>
                    <span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">up to %lld</span><span style="color:#4e9a06">&#34;</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">psync_offset</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">second_replid_offset</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
            <span style="color:#000;font-weight:bold">}</span>
        <span style="color:#000;font-weight:bold">}</span> <span style="color:#204a87;font-weight:bold">else</span> <span style="color:#000;font-weight:bold">{</span>
            <span style="color:#000">serverLog</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">LL_NOTICE</span><span style="color:#000;font-weight:bold">,</span><span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">Full resync requested by slave %s</span><span style="color:#4e9a06">&#34;</span><span style="color:#000;font-weight:bold">,</span>
                <span style="color:#000">replicationGetSlaveName</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">c</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
        <span style="color:#000;font-weight:bold">}</span>
        <span style="color:#204a87;font-weight:bold">goto</span> <span style="color:#000">need_full_resync</span><span style="color:#000;font-weight:bold">;</span>
    <span style="color:#000;font-weight:bold">}</span>

    <span style="color:#8f5902;font-style:italic">/* We still have the data our slave is asking for? */</span>
    <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#ce5c00;font-weight:bold">!</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog</span> <span style="color:#ce5c00;font-weight:bold">|</span><span style="color:#ce5c00;font-weight:bold">|</span>
        <span style="color:#000">psync_offset</span> <span style="color:#ce5c00;font-weight:bold">&lt;</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_off</span> <span style="color:#ce5c00;font-weight:bold">|</span><span style="color:#ce5c00;font-weight:bold">|</span>
        <span style="color:#000">psync_offset</span> <span style="color:#ce5c00;font-weight:bold">&gt;</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_off</span> <span style="color:#ce5c00;font-weight:bold">+</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">repl_backlog_histlen</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">)</span>
    <span style="color:#000;font-weight:bold">{</span>
        <span style="color:#000">serverLog</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">LL_NOTICE</span><span style="color:#000;font-weight:bold">,</span>
            <span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">Unable to partial resync with slave %s for lack of backlog (Slave request was: %lld).</span><span style="color:#4e9a06">&#34;</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">replicationGetSlaveName</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">c</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">psync_offset</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
        <span style="color:#204a87;font-weight:bold">if</span> <span style="color:#000;font-weight:bold">(</span><span style="color:#000">psync_offset</span> <span style="color:#ce5c00;font-weight:bold">&gt;</span> <span style="color:#000">server</span><span style="color:#000;font-weight:bold">.</span><span style="color:#000">master_repl_offset</span><span style="color:#000;font-weight:bold">)</span> <span style="color:#000;font-weight:bold">{</span>
            <span style="color:#000">serverLog</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">LL_WARNING</span><span style="color:#000;font-weight:bold">,</span>
                <span style="color:#4e9a06"></span><span style="color:#4e9a06">&#34;</span><span style="color:#4e9a06">Warning: slave %s tried to PSYNC with an offset that is greater than the master replication offset.</span><span style="color:#4e9a06">&#34;</span><span style="color:#000;font-weight:bold">,</span> <span style="color:#000">replicationGetSlaveName</span><span style="color:#000;font-weight:bold">(</span><span style="color:#000">c</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">)</span><span style="color:#000;font-weight:bold">;</span>
        <span style="color:#000;font-weight:bold">}</span>
        <span style="color:#204a87;font-weight:bold">goto</span> <span style="color:#000">need_full_resync</span><span style="color:#000;font-weight:bold">;</span>
    <span style="color:#000;font-weight:bold">}</span>
    
</code></pre></div>
    </div>
    <footer class="post-footer">
     

     <div class="post-nav">
    <div class="post-nav-next post-nav-item">
    
        <a href="http://www.shutdown.cn/post/redis4.0%E6%96%B0%E7%89%B9%E6%80%A7%E4%B8%89-lazy-free/" rel="next" title="">
        <i class="fa fa-chevron-left"></i> 
        </a>
    
    </div>

    <div class="post-nav-prev post-nav-item">
    
        <a href="http://www.shutdown.cn/post/redis4.0%E6%96%B0%E7%89%B9%E6%80%A7%E4%BA%94-%E5%9F%BA%E4%BA%8Elfu%E7%9A%84%E7%83%AD%E7%82%B9key%E5%8F%91%E7%8E%B0%E6%9C%BA%E5%88%B6/" rel="prev" title="">
         <i class="fa fa-chevron-right"></i>
        </a>
    
    </div>
</div>
      
     
     
     






    </footer>
  </article>
</section>

          </div>
        </div>
        <div class="sidebar-toggle">
  <div class="sidebar-toggle-line-wrap">
    <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
  </div>
</div>
<aside id="sidebar" class="sidebar">
  <div class="sidebar-inner">

    <section class="site-overview sidebar-panel  sidebar-panel-active ">
      <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
        src="http://www.shutdown.cn/img/author.jpg"
        alt="不与天斗Domino" />
    <p class="site-author-name" itemprop="name">不与天斗Domino</p>
    <p class="site-description motion-element" itemprop="description"> 
        Programmer &amp; Architect</p>
</div>
      <nav class="site-state motion-element">
    <div class="site-state-item site-state-posts">
      <a href="http://www.shutdown.cn/post/">
        <span class="site-state-item-count">183</span>
        <span class="site-state-item-name">日志</span>
      </a>
    </div>
    <div class="site-state-item site-state-categories">    
        <a href="http://www.shutdown.cn/categories/">      
         
        <span class="site-state-item-count">15</span>
        
        <span class="site-state-item-name">分类</span>
        
        </a>
    </div>

    <div class="site-state-item site-state-tags">
        <a href="http://www.shutdown.cn/tags/">
         
        <span class="site-state-item-count">224</span>
        
        <span class="site-state-item-name">标签</span>
        </a>
    </div>
</nav>
      
      

      

      <div class="links-of-blogroll motion-element inline">
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=&amp;m=0&amp;s=220&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33&amp;bv=35" async="async"></script>
</div>

    </section>
    
  </div>
</aside>

      </div>
    </main>
   
    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  <span itemprop="copyrightYear">  &copy; 
  2013 - 2023</span>
  <span class="with-love"><i class="fa fa-heart"></i></span>
  <span class="author" itemprop="copyrightHolder">天地维杰网</span>
  <span class="icp" itemprop="copyrightHolder"><a href="https://beian.miit.gov.cn/" target="_blank">京ICP备13019191号-1</a></span>
</div>
<div class="powered-by">
  Powered by - <a class="theme-link" href="http://gohugo.io" target="_blank" title="hugo" >Hugo v0.63.2</a>
</div>
<div class="theme-info">
  Theme by - <a class="theme-link" href="https://github.com/xtfly/hugo-theme-next" target="_blank"> NexT
  </a>
</div>


      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
      <span id="scrollpercent"><span>0</span>%</span>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/fastclick/lib/fastclick.min.js?v=1.0.6"></script> 
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="http://www.shutdown.cn/js/vendor/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>

<script src="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.pack.js?v=2.1.5"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/utils.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/motion.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/affix.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/schemes/pisces.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/scrollspy.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/post-details.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/toc.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/bootstrap.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
      inlineMath: [ ['$','$'] ],
      displayMath: [ ['$$','$$'] ],
      processEscapes: true
    },
    "HTML-CSS": { fonts: ["TeX"] }
  });
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML' async></script>
</body>
</html>